<template>
	<view class="order-confirm-page">
		<!-- 导航栏 -->
		<u-navbar :is-back="true" title="确认订单" :background="{ color: '#0096FF' }"
			:title-style="{ color: '#FFFFFF' }"></u-navbar>

		<!-- 配送方式切换 -->
		<view class="delivery-method">
			<view class="delivery-item" @click="handleHome">配送到家</view>
			<view class="delivery-item active">门店自提</view>
		</view>

		<!-- 自提点信息 -->
		<view class="pickup-section">
			<view class="pickup-title">自提点</view>
			<view class="pickup-name" @click="togglePopup">
				{{ selectedPickup.name }}
				<image class="store-img" src="/static/大于号.png"></image>
			</view>

			<view class="pickup-address" @click="togglePopup">
				{{ selectedPickup.storeAddress }}
			</view>


			<view class="contact-info">
				<view class="contact-item">
					<text class="contact-label">联系人</text>
					<input class="contact-input" v-model="contactName" placeholder="请输入联系人姓名" />
				</view>
				<view class="contact-item">
					<text class="contact-label">预留手机号</text>
					<input class="contact-input" v-model="contactPhone" placeholder="请输入手机号" />
				</view>
			</view>

			<view class="pickup-time" @click="showTimePicker">
				<view class="time-label">自提时间</view>
				<view class="time-value">{{ selectedDate }} {{ selectedTime }}</view>
				<image class="store-img" src="/static/大于号.png"></image>
			</view>
		</view>

		<!-- 商品列表 -->
		<view class="goods-section">


			<view class="goods-list">
				<block v-for="(item, index) in goodsToShow" :key="index">
					<view class="goods-item">
						<view class="goods-image">
							<image :src="item.productImageUrl" mode="aspectFit"></image>
						</view>
						<view class="goods-info">
							<text class="goods-name">{{ item.name }}</text><br>
							<text class="goods-price">¥{{ item.price }}</text>
						</view>
						<view class="goods-count">x{{ item.quantity }}</view>
					</view>
				</block>
			</view>

			<view class="goods-total">
				<view class="total-label">
					<button class="show-more-btn" @click="toggleGoods">共{{ goodsList.length  }}件</button>
					<image v-if="!isExpanded" class="store-img" src="/static/展开.png"></image>
					<image v-else class="store-img" src="/static/闭合.png"></image>
				</view>
			</view>
		</view>

		<!-- 费用明细 -->
		<view class="fee-section">
			<view class="fee-item">
				<text class="fee-label">商品金额</text>
				<text class="fee-value">¥{{ totalGoodsAmount.toFixed(2) }}</text>
			</view>
			<view class="fee-item coupon">
				<text class="fee-label">优惠券</text>
				<view class="coupon-info">
					<text>暂无可用</text>
					<u-icon name="arrow-right" size="24" color="#999"></u-icon>
				</view>
			</view>
			<view class="fee-total">
				<text class="total-label">小计：</text>
				<text class="total-value">¥{{ totalAmount }}</text>
			</view>
		</view>

		<!-- 支付按钮 -->
		<view class="payment-section">
			<button class="payment-btn" @click="handlePay">微信支付 ¥{{ totalAmount }}</button>
		</view>

		<!-- 时间选择器 -->
		<view class="time-picker" v-if="showPicker">
			<view class="time-picker-header">
				<view class="time-picker-close" @click="closeTimePicker">×</view>
				<view class="time-picker-title">选择时间</view>
			</view>
			<view class="time-picker-content">
				<view class="date-column">
					<!-- 显示今天的日期 -->
					<view class="date-item" :class="{ active: selectedDate === today }" @click="selectDate(today)">
						{{ today }} {{ weekDays[new Date().getDay()] }}
					</view>
					<!-- 显示明天的日期 -->
					<view v-if="isTomorrowAvailable" class="date-item" :class="{ active: selectedDate === tomorrow }"
						@click="selectDate(tomorrow)">
						{{ tomorrow }} {{ weekDays[new Date(new Date().getTime() + 24 * 60 * 60 * 1000).getDay()] }}
					</view>
				</view>
				<view class="time-column">
					<view class="time-slot" v-for="(slot, index) in filteredTimeSlots" :key="index"
						@click="selectTimeSlot(slot)">
						<view class="time-range">{{ slot.timeRange }}</view>
						<view class="delivery-fee">{{ slot.fee }}</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 门店选择弹出层 -->
		<view class="store-picker" v-if="showStorePicker">
			<view class="store-picker-header">
				<view class="store-picker-close" @click="closeStorePicker">×</view>
				<view class="store-picker-title">选择门店</view>
			</view>
			<view class="store-picker-content">
				<view class="store-item" v-for="(store, index) in stores" :key="index" @click="selectStore(store)">
					<text class="store-item-name">{{ store.storeName }}</text><br>
					<text class="store-item-name">{{ store.storeAddress }}</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		onMounted
	} from 'vue';
	import {
		mapState,
		mapGetters,
		mapMutations,
		mapActions
	} from 'vuex';
	import store from '../../store';

	const goodsList = ref([]); // 商品列表
	const showCount = ref(2); // 默认显示的商品数量
	const isTomorrowAvailable = ref(true);
	const isExpanded = ref(false);
	const showPicker = ref(false);
	const showStorePicker = ref(false);
	const selectedDate = ref('');
	const selectedTime = ref(''); // 当前选中的时间
	const weekDays = ref(['周日', '周一', '周二', '周三', '周四', '周五', '周六']); // 星期几
	const timeSlots = ref([{
			timeRange: '09:00-09:30',
			fee: '免服务费'
		},
		{
			timeRange: '09:30-10:00',
			fee: '免服务费'
		},
		{
			timeRange: '10:00-10:30',
			fee: '免服务费'
		},
		{
			timeRange: '10:30-11:00',
			fee: '免服务费'
		},
		{
			timeRange: '11:00-11:30',
			fee: '免服务费'
		},
		{
			timeRange: '11:30-12:00',
			fee: '免服务费'
		},
		{
			timeRange: '12:00-12:30',
			fee: '免服务费'
		},
		{
			timeRange: '12:30-13:00',
			fee: '免服务费'
		},
		{
			timeRange: '13:30-14:00',
			fee: '免服务费'
		},
		{
			timeRange: '14:00-15:00',
			fee: '免服务费'
		},
		{
			timeRange: '15:30-16:00',
			fee: '免服务费'
		},
		{
			timeRange: '16:30-17:00',
			fee: '免服务费'
		},
		{
			timeRange: '17:30-18:00',
			fee: '免服务费'
		},
		{
			timeRange: '18:30-19:00',
			fee: '免服务费'
		},
		{
			timeRange: '19:30-20:00',
			fee: '免服务费'
		}
	]);
	const contactName = ref(''); // 联系人姓名
	const contactPhone = ref(''); // 联系电话
	const stores = ref([]); // 从后端获取的门店数据
	const selectedStore = ref({}); // 当前选中的门店
	const filteredTimeSlots = ref([]); // 过滤后的时间槽
	const selectedPickup = ref({
		name: '',
		storeAddress: ''
	}); // 初始化选中的自提点

	const goodsToShow = computed(() => {
		return isExpanded.value ? goodsList.value : goodsList.value.slice(0, showCount.value);
	});

	const today = computed(() => {
		const date = new Date();
		return `${date.getMonth() + 1}月${date.getDate()}日`;
	});

	const tomorrow = computed(() => {
		const date = new Date();
		date.setDate(date.getDate() + 1);
		return `${date.getMonth() + 1}月${date.getDate()}日`;
	});

	// 判断是否是当天
	const isCurrentDate = computed(() => {
		return selectedDate.value === today.value;
	});

	const totalGoodsAmount = computed(() => {
		return goodsList.value.reduce((acc, item) => {
			return acc + parseFloat(item.price) * item.quantity;
		}, 0);
	});

	const totalQuantity = computed(() => { // 总数量
		return goodsList.value.reduce((acc, item) => acc + item.quantity, 0);
	});

	const totalAmount = computed(() => {
		return totalGoodsAmount.value;
	});

	onMounted(() => {
		goodsList.value = store.state.cart;
	});

	const fetchStores = async () => {
		const app = getApp();
		const url = app.globalData.url;
		try {
			const response = await uni.request({
				url: url + "USER-SERVICE/store/selectSePurchase",
				method: 'GET'
			});
			console.log('Response:', response); // 打印响应内容

			if (response && response.statusCode === 200 && response.data) {
				stores.value = response.data;
				// 设置默认选中第一个门店
				if (stores.value.length > 0) {
					selectedStore.value = stores.value[0];
					selectedPickup.value = {
						name: selectedStore.value.storeName,
						storeAddress: selectedStore.value.storeAddress // 假设门店数据中有 address 属性
					};
				}
			} else {
				console.error('获取门店数据失败:', response ? JSON.stringify(response) : 'No response data');
				uni.showToast({
					title: '获取门店数据失败',
					icon: 'none'
				});
			}
		} catch (error) {
			console.error('请求错误:', error);
			uni.showToast({
				title: '网络请求失败，请检查地址是否正确',
				icon: 'none'
			});
		}
	};

	const toggleGoods = () => {
		isExpanded.value = !isExpanded.value;
	};

	// 切换弹出层显示状态
	const togglePopup = () => {
		showStorePicker.value = !showStorePicker.value;
	};

	// 关闭弹出层
	const closeStorePicker = () => {
		showStorePicker.value = false;
	};

	// 选择自提点
	const selectStore = (store) => {
	  selectedStore.value = store;
	  selectedPickup.value = {
	    name: store.storeName,
	    storeAddress: store.storeAddress,
	    storeId: store.storeId // 确保获取门店 ID
	  };
	  showStorePicker.value = false;
	};

	const showTimePicker = () => {
		showPicker.value = true;
		filterTimeSlots();
	};

	const closeTimePicker = () => {
		showPicker.value = false;
	};

	const selectTimeSlot = (slot) => {
		selectedTime.value = slot.timeRange;
		closeTimePicker();
	};

	const selectDate = (date) => {
		selectedDate.value = date;
		filterTimeSlots();
		setDefaultTime();
	};

	const filterTimeSlots = () => {
		const now = new Date();
		const currentHour = now.getHours();
		const currentMinute = now.getMinutes();

		filteredTimeSlots.value = timeSlots.value.filter(slot => {
			const [startHour, startMinute] = slot.timeRange.split('-')[0].split(':').map(Number);

			if (isCurrentDate.value) {
				return startHour > currentHour || (startHour === currentHour && startMinute >= currentMinute);
			} else {
				return true; // 如果是明天，显示所有时间槽
			}
		});
	};

	const setDefaultTime = () => {
		const now = new Date();
		const currentHour = now.getHours();
		const currentMinute = now.getMinutes();

		if (isCurrentDate.value) {
			selectedTime.value = filteredTimeSlots.value.find(slot => {
				const [startHour, startMinute] = slot.timeRange.split('-')[0].split(':').map(Number);
				return startHour === currentHour && startMinute === currentMinute;
			})?.timeRange || filteredTimeSlots.value[0]?.timeRange || '';
		} else {
			selectedTime.value = timeSlots.value[0]?.timeRange || '';
		}
	};

	// 获取门店数据
	fetchStores(); // 加载门店数据

	// 设置默认日期和时间
	selectedDate.value = today.value;
	filterTimeSlots();
	setDefaultTime();
	
	
	const handlePay = async () => {
	  // 准备发送到后端的数据
	  const salesOrderData = {
		storeId:selectedPickup.value.storeId,
	    pickupStoreId:selectedPickup.value.storeId, // 门店 ID
	    customerId: 1, // 客户 ID，默认为 1
	    amountDue: totalAmount.value, // 应收金额
	    discountAmount: 0, // 折扣金额，默认为 0
	    actualReceivedAmount: totalAmount.value, // 实际收款金额
	    pendingAmount: 0, // 待收款金额，默认为 0
	    paymentStatus: "1", // 支付状态，默认为已支付
	    remarks: "", // 备注，可选
	    employeeId: 1, // 业务员 ID，默认为 1
	    deliveryType:  "STORE" , // 配送方式
		contactName: contactName.value, // 联系人姓名
		    contactPhone: contactPhone.value, // 联系电话

	    pickupTime: formatDateTime(selectedDate.value, selectedTime.value), // 配送时间
		orderDetails: goodsToShow.value.map(item => ({
		  productId: item.productId, // 确保是数字
		  quantity: item.quantity, // 确保是数字
		  unitPrice: item.price // 确保是数字
		}))
	  };
	
	  try {
	    const response = await uni.request({
	      url: 'http://localhost:15000/SALE-SERVICE/sale/createAllWX', // 替换为你的后端接口地址
	      method: 'POST',
	      data: salesOrderData,
	      header: {
	        'Content-Type': 'application/json'
	      }
	    });
	
	    if (response.data!=null) {
	      uni.showToast({
	        title: '支付成功',
	        icon: 'success',
			duration:1000
	      });
	      // 清空购物车或其他后续操作
        store.dispatch("clearProducts");
        uni.switchTab({
            url: '/pages/index/index'
          });
	    } else {
	      uni.showToast({
	        title: '支付失败',
	        icon: 'none'
	      });
	    }
	  } catch (error) {
	    console.error('支付请求失败:', error);
	    uni.showToast({
	      title: '支付请求失败',
	      icon: 'none'
	    });
	  }
	};
	// 判断当前页面是否是 home 页面
	const isHomeDelivery = ref(true);
	
	
	const handleHome = () => {
	  uni.navigateTo({
	    url: '/pages/distribution-home/distribution-home'
	  });
	  isHomeDelivery.value = false;
	};
	
	
	const handleSelf = () => {
	  uni.navigateTo({
	    url: '/pages/distribution-self/distribution-self'
	  });
	  isHomeDelivery.value = true;
	};
	function formatDateTime(date, time) {
	  const formattedDate = `${date}T${time}:00`;
	  return formattedDate;
	}
</script>

<style scoped>
	.order-confirm-page {
		background-color: #f5f5f5;
		min-height: 100vh;
		padding-bottom: 60px;
		/* 为支付按钮留出空间 */
	}

	.delivery-method {
		display: flex;
		background-color: #fff;
		margin-bottom: 10px;
	}

	.delivery-item {
		flex: 1;
		padding: 15px 0;
		text-align: center;
		font-size: 16px;
		color: #333;
		position: relative;
	}

	.delivery-item.active {
		color: #0096FF;
		font-weight: bold;
	}

	.pickup-section {
		background-color: #fff;
		padding: 15px;
		margin-bottom: 10px;
	}

	.pickup-title {
		font-size: 14px;
		color: #999;
		margin-bottom: 10px;
	}

	.pickup-name {
		font-size: 18px;
		color: #333;
		margin-bottom: 10px;
		display: flex;
		align-items: center;
		cursor: pointer;
	}

	.store-img {
		width: 15px;
		height: 15px;
		margin-left: 5px;
	}

	.pickup-address {
		font-size: 14px;
		color: #666;
		margin-bottom: 15px;
		line-height: 1.5;
		cursor: pointer;
	}

	.contact-info {
		margin-bottom: 15px;
	}

	.contact-item {
		display: flex;
		margin-bottom: 10px;
	}

	.contact-label {
		font-size: 14px;
		color: #999;
		width: 70px;
	}

	.contact-input {
		flex: 1;
		font-size: 14px;
		color: #333;
		border: 1px solid #eee;
		padding: 5px 10px;
		border-radius: 4px;
	}

	.pickup-time {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding-top: 15px;
		border-top: 1px solid #eee;
		cursor: pointer;
	}

	.time-label {
		font-size: 14px;
		color: #999;
	}

	.time-value {
		font-size: 14px;
		color: #0096FF;
	}

	.goods-section {
		background-color: #fff;
		padding: 15px;
		margin-bottom: 10px;
	}

	.goods-list {
		margin-bottom: 10px;
	}

	.goods-item {
		display: flex;
		padding: 10px 0;
		border-bottom: 1px solid #eee;
	}

	.goods-image {
		width: 80px;
		height: 80px;
		margin-right: 15px;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.goods-image image {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.goods-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: center;
	}

	.goods-name {
		font-size: 14px;
		color: #333;
		margin-bottom: 5px;
	}

	.goods-price {
		font-size: 16px;
		color: #FF5722;
		margin-top: auto;
	}

	.goods-count {
		font-size: 14px;
		color: #999;
		margin-left: auto;
		display: flex;
		align-items: center;
	}

	.goods-total {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 10px 0;
	}

	.total-label {
		display: flex;
		align-items: center;
		font-size: 14px;
		color: #999;
	}

	.fee-section {
		background-color: #fff;
		padding: 15px;
		margin-bottom: 10px;
	}

	.fee-item {
		display: flex;
		justify-content: space-between;
		padding: 10px 0;
		border-bottom: 1px solid #eee;
	}

	.fee-label {
		font-size: 14px;
		color: #666;
	}

	.fee-value {
		font-size: 14px;
		color: #333;
	}

	.coupon {
		border-bottom: none;
	}

	.coupon-info {
		display: flex;
		align-items: center;
		color: #0096FF;
		font-size: 14px;
	}

	.fee-total {
		display: flex;
		justify-content: flex-end;
		padding: 15px 0;
	}

	.total-label {
		font-size: 16px;
		color: #333;
	}

	.total-value {
		font-size: 18px;
		color: #FF5722;
		font-weight: bold;
		margin-left: 5px;
	}

	.payment-section {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		padding: 15px;
		background-color: #fff;
		z-index: 100;
	}

	.payment-btn {
		width: 100%;
		height: 48px;
		background-color: #0096FF;
		color: #fff;
		border: none;
		border-radius: 24px;
		font-size: 16px;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.show-more-btn {
		padding: 0;
		margin: 0;
		background: none;
		border: none;
		color: #333;
		font-size: 14px;
	}

	/* 时间选择器样式 */
	.time-picker {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		z-index: 1000;
		display: flex;
		flex-direction: column;
	}

	.time-picker-header {
		background-color: #fff;
		padding: 15px;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.time-picker-close {
		font-size: 20px;
		color: #999;
	}

	.time-picker-title {
		font-size: 16px;
		font-weight: bold;
	}

	.time-picker-content {
		flex: 1;
		background-color: #fff;
		display: flex;
		overflow-y: auto;
	}

	.date-column {
		width: 100px;
		border-right: 1px solid #eee;
	}

	.date-item {
		padding: 15px;
		text-align: center;
		font-size: 14px;
		color: #333;
	}

	.date-item.active {
		color: #0096FF;
		font-weight: bold;
	}

	.time-column {
		flex: 1;
		padding: 15px;
	}

	.time-slot {
		padding: 15px 0;
		border-bottom: 1px solid #eee;
	}

	.time-range {
		font-size: 16px;
		color: #333;
		margin-bottom: 5px;
	}

	.delivery-fee {
		font-size: 14px;
		color: #0096FF;
	}

	/* 门店选择器样式 */
	.store-picker {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		z-index: 1000;
		display: flex;
		flex-direction: column;
	}

	.store-picker-header {
		background-color: #fff;
		padding: 15px;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.store-picker-close {
		font-size: 20px;
		color: #999;
	}

	.store-picker-title {
		font-size: 16px;
		font-weight: bold;
	}

	.close-btn {
		color: #ff5757;
		font-size: 16px;
		margin-bottom: 15px;
		display: block;
	}

	.popup-title {
		font-size: 18px;
		color: #333;
		margin-bottom: 20px;
		text-align: center;
	}

	.store-picker-content {
		flex: 1;
		background-color: #fff;
		overflow-y: auto;
	}

	.store-item {
		padding: 15px;
		border-bottom: 1px solid #eee;
	}

	.store-item-name {
		font-size: 16px;
		color: #333;
	}
</style>